@echo off
:: Force to script directory to prevent C:\Windows\System32 issue
pushd "%~dp0"

:: Set color - green text
color 0A

echo ==========================================
echo   Star Resonance DPS Counter
echo       One-Click Launcher
echo ==========================================
echo [INFO] Complete startup with smart cleanup
echo [INFO] Starting server + browser + overlay...
echo.

:: Create log file
echo [%date% %time%] One-click startup started > launch.log

:: Check environment
echo [CHECK] Checking runtime environment...
echo [%date% %time%] Checking Node.js >> launch.log
node --version >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Node.js not found!
    echo [TIPS] Please install Node.js from: https://nodejs.org/
    echo [%date% %time%] ERROR: Node.js not found >> launch.log
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

for /f "tokens=*" %%i in ('node --version') do (
    echo [SUCCESS] Node.js: %%i
    echo [%date% %time%] Node.js version: %%i >> launch.log
)

:: Check main project dependencies
echo [CHECK] Checking main project dependencies...
echo [%date% %time%] Checking main project node_modules >> launch.log
if not exist "node_modules" (
    echo [WARNING] Main project dependencies not installed, installing...
    echo [%date% %time%] Installing main project dependencies >> launch.log
    echo [INFO] Running install.bat...
    call install.bat
    if !errorLevel! neq 0 (
        echo [ERROR] Main project dependency installation failed!
        echo [%date% %time%] ERROR: Main project install failed >> launch.log
        echo.
        echo Press any key to exit...
        pause >nul
        exit /b 1
    )
) else (
    echo [SUCCESS] Main project dependencies installed
    echo [%date% %time%] Main project dependencies found >> launch.log
)

:: Check floating overlay dependencies
echo [CHECK] Checking floating overlay dependencies...
echo [%date% %time%] Checking floating_overlay >> launch.log
if not exist "floating_overlay" (
    echo [ERROR] Floating overlay directory not found!
    echo [%date% %time%] ERROR: floating_overlay directory not found >> launch.log
    echo [TIPS] Please ensure all files are properly extracted
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

cd floating_overlay
if not exist "node_modules" (
    echo [WARNING] Floating overlay dependencies not installed
    echo [INFO] Desktop overlay will not be available
    echo [SOLUTION] Run install.bat to install all components
    echo [%date% %time%] Overlay dependencies missing, continuing without overlay >> launch.log
    cd ..
    goto skip_overlay_check
) else (
    echo [SUCCESS] Floating overlay dependencies installed
    echo [%date% %time%] Overlay dependencies found >> launch.log
)
cd ..

:skip_overlay_check

:: Smart port cleanup - automatically handle all port conflicts
echo [CHECK] Checking and cleaning ports...
echo [%date% %time%] Starting smart port cleanup >> launch.log

:: Always perform comprehensive cleanup to ensure clean start
echo [CLEANUP] Performing comprehensive process cleanup...

:: Method 1: Terminate all related processes by name
echo [INFO] Terminating Node.js and Electron processes...
taskkill /f /im node.exe >nul 2>&1
taskkill /f /im electron.exe >nul 2>&1

:: Method 2: Find and terminate processes using port 8989
echo [INFO] Freeing port 8989...
for /f "tokens=5" %%i in ('netstat -ano ^| find ":8989" ^| find "LISTENING"') do (
    echo [ACTION] Terminating process PID: %%i
    taskkill /f /pid %%i >nul 2>&1
)

:: Method 3: Use WMIC for stubborn processes
wmic process where "name='node.exe'" delete >nul 2>&1

:: Method 4: Clean any other related processes that might interfere
taskkill /f /im "Star Resonance*" >nul 2>&1
taskkill /f /im "星痕共鸣*" >nul 2>&1

:: Wait for cleanup to complete
echo [INFO] Waiting for cleanup to complete...
timeout /t 3 >nul

:: Verify port is available (but don't block if still occupied)
netstat -an | find ":8989" >nul 2>&1
if %errorLevel% equ 0 (
    echo [WARNING] Port 8989 still in use, but continuing startup...
    echo [INFO] The new instance may automatically handle port conflicts
) else (
    echo [SUCCESS] Port 8989 is now available
)

echo [%date% %time%] Port cleanup completed >> launch.log

echo.
echo ========================================
echo        Starting Services
echo ========================================
echo.

:: Check if server_wrapper.js exists
if not exist "server_wrapper.js" (
    echo [WARNING] server_wrapper.js not found, using server.js
    echo [%date% %time%] server_wrapper.js not found, using server.js >> launch.log
    set SERVER_SCRIPT=server.js
) else (
    set SERVER_SCRIPT=server_wrapper.js
)

:: Create server input file
echo [PREPARE] Creating auto input configuration...
echo [%date% %time%] Creating server input file >> launch.log

:: Use Node.js to create standardized config file
echo [INFO] Using standardized config generator...
node create_config.js >config_output.log 2>&1
if %errorLevel% equ 0 (
    echo [SUCCESS] Config file generated successfully
    echo [%date% %time%] Config generated with Node.js >> launch.log
) else (
    echo [WARNING] Node.js config generator failed, using fallback method...
    echo [%date% %time%] Node.js config generator failed, using fallback >> launch.log
    
    :: Fallback method: delete old config file to avoid format issues
    if exist server_input.txt del server_input.txt >nul 2>&1
    
    :: Use standard method to create config file
    (
    echo 3
    echo info
    ) > server_input.txt
)

:: Verify config file creation
if exist server_input.txt (
    echo [SUCCESS] Auto input configuration ready - device 3, log level info
    echo [DEBUG] Config file content:
    type server_input.txt
    echo.
    echo [%date% %time%] Config file verified >> launch.log
) else (
    echo [ERROR] Config file creation failed!
    echo [%date% %time%] ERROR: Config file creation failed >> launch.log
    goto error_exit
)

:: Start main server (background) - use server_wrapper.js for automation
echo [START] Starting main server...
echo [%date% %time%] Starting main server with %SERVER_SCRIPT% >> launch.log

:: Clear possible existing server_output.log
if exist server_output.log del server_output.log >nul 2>&1

:: Use more reliable startup method
if "%SERVER_SCRIPT%"=="server_wrapper.js" (
    echo [INFO] Using server_wrapper.js for automated startup
    start /b cmd /c "node server_wrapper.js > server_output.log 2>&1"
) else (
    echo [INFO] Using server.js direct startup
    start /b cmd /c "echo 3&echo info | node server.js > server_output.log 2>&1"
)

:: Wait for server startup
echo [WAIT] Waiting for server startup...
echo [%date% %time%] Waiting for server >> launch.log
set /a counter=0
:wait_server
timeout /t 2 >nul
set /a counter+=1

:: Check if server output file exists and has content
if exist server_output.log (
    :: Check for server startup success information first
    findstr /C:"Web Server started at" server_output.log >nul 2>&1
    if %errorLevel% equ 0 (
        echo [SUCCESS] Server startup detected in log!
        goto server_ready
    )
    
    :: Check for other startup information
    findstr /C:"Welcome!" server_output.log >nul 2>&1
    if %errorLevel% equ 0 (
        echo [INFO] Server is initializing...
    )
    
    :: Only check for critical errors, not all errors
    findstr /C:"FATAL\|Cannot find module\|EADDRINUSE" server_output.log >nul 2>&1
    if %errorLevel% equ 0 (
        echo [ERROR] Critical server startup error detected!
        echo [%date% %time%] ERROR: Critical server startup error detected >> launch.log
        echo ======================== Error Log ========================
        type server_output.log
        echo ======================== End Error Log ========================
        goto server_error
    )
)

:: Check if port is listening (server ready)
netstat -an | find ":8989" | find "LISTENING" >nul 2>&1
if %errorLevel% equ 0 (
    echo [SUCCESS] Server port 8989 is listening!
    goto server_ready
)

:: Check if Node.js process is running
tasklist | find "node.exe" >nul 2>&1
if %errorLevel% equ 0 (
    echo [INFO] Node.js process is running...
)

if %counter% lss 20 (
    echo [WAIT] Waiting... [%counter%/20] - Checking server startup status
    goto wait_server
) else (
    echo [ERROR] Server startup timeout!
    echo [%date% %time%] ERROR: Server startup timeout >> launch.log
    goto server_error
)

:server_error
echo [DEBUG] Server startup failed, showing detailed information:
echo ======================== Server Log ========================
if exist server_output.log (
    type server_output.log
) else (
    echo [ERROR] Server output log file does not exist!
)
echo ======================== End Log ========================
echo.
echo [DEBUG] Currently running Node.js processes:
tasklist | find "node.exe"
echo.
echo [DEBUG] Port 8989 usage:
netstat -an | find ":8989"
echo.
echo [SOLUTIONS] Possible solutions:
echo   1. Check if Node.js is properly installed
echo   2. Check if project dependencies are completely installed
echo   3. Check if firewall is blocking Node.js
echo   4. Try running as administrator
echo   5. Check if port 8989 is occupied by other programs
echo.
echo Press any key to exit...
pause >nul
exit /b 1

:server_ready

echo [SUCCESS] Main server started successfully!
echo [%date% %time%] Main server started successfully >> launch.log

:: Wait a bit to ensure server is fully ready
timeout /t 2 >nul

:: Start browser (client)
echo [START] Opening browser client...
echo [%date% %time%] Opening browser >> launch.log
start http://localhost:8989

:: Wait for browser to load
echo [INFO] Browser client starting at http://localhost:8989
echo [INFO] This is the main client interface for the DPS counter
timeout /t 3 >nul

:: Start floating overlay
echo [START] Starting floating overlay...
echo [%date% %time%] Starting floating overlay >> launch.log

:: Check floating overlay directory and dependencies
if not exist "floating_overlay\main.js" (
    echo [INFO] Overlay files not found, skipping desktop overlay
    echo [%date% %time%] Overlay files missing, skipping >> launch.log
) else if not exist "floating_overlay\node_modules\electron" (
    echo [INFO] Desktop overlay not installed, skipping overlay startup
    echo [SUGGESTION] Run install.bat to enable desktop overlay feature
    echo [%date% %time%] Overlay dependencies missing, skipping >> launch.log
) else (
    cd floating_overlay
    
    :: Use npx electron directly to avoid script issues
    echo [DEBUG] Starting desktop overlay...
    echo [%date% %time%] Using direct electron startup >> launch.log
    start /b cmd /c "npx electron . --no-sandbox --disable-web-security > overlay_output.log 2>&1"
    
    :: Wait for overlay startup
    echo [WAIT] Waiting for overlay startup...
    timeout /t 3 >nul
    
    cd ..
)

echo.
echo ========================================
echo          Startup Complete!
echo ========================================
echo.
echo [SUCCESS] All services started successfully!
echo [%date% %time%] All services started successfully >> launch.log
echo.
echo Browser Client: http://localhost:8989

:: Check what components actually started
if exist "floating_overlay\node_modules\electron" (
    echo Desktop Overlay: Started (may take a few seconds to display)
    echo.
    echo [INFO] Components started:
    echo   - Server: DPS calculation and data processing backend
    echo   - Browser Client: Complete data display and control interface  
    echo   - Desktop Overlay: Real-time view in game, supports transparency and timer
) else (
    echo Desktop Overlay: Not available (not installed)
    echo.
    echo [INFO] Components started:
    echo   - Server: DPS calculation and data processing backend
    echo   - Browser Client: Complete data display and control interface
    echo.
    echo [NOTE] Desktop overlay not installed
    echo [TIP] Run install.bat to enable desktop overlay feature
)
echo.
echo [TIPS] How to close:
echo   - Closing this window will stop all services
echo   - Or manually close browser and overlay
echo.
echo [LOG] Detailed logs saved in:
echo   - launch.log (startup log)
echo   - server_output.log (server log)  
echo   - floating_overlay/overlay_output.log (overlay log)
echo.
echo Monitoring service status...
echo [INFO] Press Ctrl+C to stop all services
echo.

:: Keep window open and monitor service status
:monitor
timeout /t 10 >nul

:: 检查服务器状态
netstat -an | find ":8989" | find "LISTENING" >nul 2>&1
if %errorLevel% equ 0 (
    set "SERVER_STATUS=Running"
) else (
    set "SERVER_STATUS=Stopped"
)

:: 检查覆盖层状态
tasklist /fi "imagename eq electron.exe" | find "electron.exe" >nul 2>&1
if %errorLevel% equ 0 (
    set "OVERLAY_STATUS=Running"
) else (
    set "OVERLAY_STATUS=Stopped"
)

echo [%time%] Service monitoring... Browser: http://localhost:8989 (Server: %SERVER_STATUS%) Overlay: %OVERLAY_STATUS%

:: 如果覆盖层停止了，提示用户
if "%OVERLAY_STATUS%"=="Stopped" (
    echo [WARNING] 覆盖层已停止运行！
    echo [TIP] 可能原因：窗口被关闭、进程崩溃、或窗口不可见
    echo [TIP] 尝试运行 floating_overlay\start_overlay_improved.bat 重新启动
)

goto monitor

:error_exit
echo.
echo Press any key to exit...
pause >nul
popd
exit /b 1
